package com.tanhua.server.service;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.server.holder.UserHolder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    /**
     * 发送短信验证码
//     * @param phone
     */
    /*public String SendCode() {
        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);

        //2、调用template对象，发送手机短信
        //template.sendSms(phone,code);
        //3、将验证码存入到redis

    }*/

    public void sendMessage(Map map) {
        String phone = (String)map.get("phone");
        String code = "123456";
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,code, Duration.ofMinutes(5));
    }

    /*先判断验证码
    * 判断手机号(有就算了,没有就注册)
    * */
    /**
     * 验证登录
     * @param phone
     * @param //code
     */
    public Map loginVerification(String phone, String verificationCode) {
        //1、从redis中获取下发的验证码
        String CheckCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(!CheckCode.equals(verificationCode) || StringUtils.isEmpty(CheckCode)){
            //验证码无效
            throw new RuntimeException();
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if (user==null){
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
        }
        //6、通过JWT生成token(存入id和手机号码)
        Map tokeMap = new HashMap();
        tokeMap.put("id",user.getId());
        tokeMap.put("phone",user.getMobile());
        String token = JwtUtils.getToken(tokeMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;

    }


    /**
     * 修改手机号发送验证码
     * @param mobile
     */
    public void sendVerificationCode(String mobile) {
        String nestPhone = mobile;
        String nestCode = "654321";
        redisTemplate.opsForValue().set("CHECK_CODE_"+nestPhone,nestCode,Duration.ofMinutes(5));
    }


    public Boolean checkVerificationCode(String phone, String checkVerificationCode) {
        //1、从redis中获取下发的验证码
        String checkCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if ( !checkCode.equals(checkVerificationCode) || StringUtils.isEmpty(checkVerificationCode)){
            //验证码无效
            throw new RuntimeException();
        }
        return true;
    }

    public void findById(String updatePhone) {
        userApi.findByMobile(updatePhone);
    }

    public void update(Map map) {
        String phone = (String) map.get("phone");
        String mobile = UserHolder.getMobile();
        User byMobile = userApi.findByMobile(mobile);
        byMobile.setMobile(phone);
    }
}
